package com.site.weixinpay.servlet;

import com.site.weixinpay.util.PayCommonUtil;
import com.site.weixinpay.util.PayConfigUtil;
import com.site.weixinpay.util.ZxingUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Random;

public class BuyServlet extends HttpServlet {

    Random random = new Random();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户要购买的商品
        req.setCharacterEncoding("UTF-8");
        String body = req.getParameter("body"); //
        String price ="1"; // 微信的价格单位是分
        BigDecimal pirce = BigDecimal.valueOf(1);
        String orderNo = random.nextInt(100000)+"";
        // 生成二维码

        try {
            String codeUrl = PayCommonUtil.weixin_pay(price, body, orderNo);
            BufferedImage image = ZxingUtil.createImage(codeUrl, 300, 300);
            req.getSession().setAttribute("orderNo",orderNo);
            req.getSession().setAttribute("order_id",orderNo);
            req.getSession().setAttribute("image",image);
            resp.sendRedirect("/payment.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
